package org.batatasframework.bytecode;

import java.util.ArrayList;
import java.util.List;

import org.batatasframework.bytecode.spi.AsmLoadable;

/**
 * 一个方法的方法体
 * @author jackson
 *
 */
public class AsmMethodBody implements AutoCloseable{

	private final ClassAsminfo owner;
	private final MethodAsminfo method;
	private final ThisVariableAsminfo thisVariable;
	private final LocalVariableAsminfo[] arguments;
	
	private List<LocalVariableAsminfo> variables = new ArrayList<>();
//	private MethodVisitor visitor;
	
	private AsmLoadable returnValue;
	
	private int variableCount = 1;
	
	public AsmMethodBody(MethodAsminfo method){
		this.owner = method.getOwner();
		this.method = method;
		this.thisVariable = new ThisVariableAsminfo(this, owner);
		
		ClassAsminfo[] params = method.getParamClass();
		if(null != params){
			arguments = new LocalVariableAsminfo[params.length];
			for(int i = 0; i < params.length; i++){
				arguments[i] = assignVariable(params[i]);
			}
		}else{
			arguments = null;
		}
	}
	
	public ThisVariableAsminfo getThis(){
		return thisVariable;
	}
	
	public LocalVariableAsminfo getArgument(int index){
		if(0 <= index && index < arguments.length) return arguments[index];
		return null;
	}
	
	/** 分配一个新的本地变量 */
	public LocalVariableAsminfo assignVariable(ClassAsminfo info){
		LocalVariableAsminfo lva = new LocalVariableAsminfo(this, info, variableCount++);
		variables.add(lva);
		return lva;
	}
	
	/** 分配一个新的本地变量 */
	public LocalVariableAsminfo assignVariable(Class<?> info){
		return assignVariable(new ClassAsminfo(info));
	}
	
	public ClassAsminfo getOwner() {
		return owner;
	}
	
	public MethodAsminfo getMethod() {
		return method;
	}

	@Override
	public void close() throws Exception {
		// TODO Auto-generated method stub
		
	}
}
